package com.ant.storage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.FundsDto;
import com.ant.storage.mapper.PaymentMapper;
import com.ant.storage.mapper.SubscribeMapper;
import com.ant.storage.pojo.*;
import com.ant.storage.service.*;
import com.ant.storage.utils.DingDingUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taobao.api.ApiException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author melon
 * @since 2022-10-20
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements IPaymentService {

    private  static Logger log= LoggerFactory.getLogger(PaymentServiceImpl.class);
    @Resource
    SubscribeMapper subscribeMapper;

    @Resource
    IPurchaseOrdersService ordersService;

    @Resource
    IGoodsPoolService goodsPoolService;

    @Resource
    ISubscribeService subscribeService;

    @Autowired
    private IAuditListService auditListService;

    @Resource
    private IAbilityService abilityService;


    @Resource
    private IMergeProcurementService  procurementService;

    /**
     * 提交请款申请
     *
     * @param payment
     * @param bindingResult
     * @return
     */
    @Override
    @Transactional()
    public ResultVo savePayment(Payment payment, BindingResult bindingResult) {
            payment.setCreationTime(new Date());
            MergeProcurement mergeProcurement=new MergeProcurement();
            mergeProcurement.setSubscribeId(payment.getId().toString());
            mergeProcurement.setPurchaserId(Integer.parseInt(payment.getCreatorBy()));
            mergeProcurement.setApplyPrice(payment.getMoney());
            mergeProcurement.setCreationTime(new Date());
            procurementService.save(mergeProcurement);

        if (payment.getPayType().equals("38")) {
            AuditList auditList = new AuditList();
            auditList.setParentId(mergeProcurement.getId());
            auditList.setProcessType("payment");
            auditList.setCreationTime(new Date());
            // 添加审核记录 1 审核  2 抄送
            for (String str : payment.getApproval()) {
                auditList.setNameId(str);
                auditList.setTypes("1");
                auditListService.save(auditList);
            }
            for (String str2 : payment.getNotify()) {
                auditList.setNameId(str2);
                auditList.setTypes("2");
                auditListService.save(auditList);
            }
            try {
                Long personneDeplList = DingDingUtil.getPersonneDepld(payment.getUserId(),
                        DingDingUtil.obtainToken());
                Integer depid = personneDeplList.intValue();
                payment.setDeptId(depid);
            } catch (ApiException e) {
                e.printStackTrace();
            }
            //TODO 发起钉钉申请
            try {
                String process_instance_id = addDingDing(payment);
                log.info("操作成功 " +payment.getId()+":"+process_instance_id);
                if(StringUtils.isNotEmpty(process_instance_id)){
                    // 修改审批id
                    UpdateWrapper<MergeProcurement> updateWrapper = new UpdateWrapper<MergeProcurement>().set(
                            "process_instance_id", process_instance_id).eq("id", mergeProcurement.getId());
                    procurementService.update(updateWrapper);

//                    Subscribe subscribe = new Subscribe();
//                    list.stream().map(item -> {
//                        subscribe.setId(payment.getId());
//                        subscribe.setPrice(payment.getMoney());
//                        subscribe.setIsMerge(1);
//                        subscribe.setPayStatus(1);
//                        subscribe.setPayType(payment.getPaymentMethod().toString());
//
//                        purchaseOrdersService.update(new UpdateWrapper<PurchaseOrders>()
//                                .set("payment_method", mergeDto.getPaymentMethod())
//                                .eq("parent_id", item.getId()));
//                        return subscribe;
//                    }).collect(Collectors.toList());
//                    subscribeService.updateById(subscribe);

//                    UpdateWrapper<Subscribe> updateWrapper = new UpdateWrapper<Subscribe>()
//                            .set("process_instance_id", process_instance_id)
//                            .set("pay_type", payment.getPayType())
//                            .set("status", "0")
//                            .set("pay_status", 1)
//                            .set("total_price", payment.getMoney())
//                            .eq("id", payment.getId());
//                    ordersService.update(new UpdateWrapper<PurchaseOrders>().set("payment_method", payment.getPayType())
//                            .eq("parent_id", payment.getId()));
//                    goodsPoolService.update(new UpdateWrapper<GoodsPool>().set("status", 3)
//                            .eq("id", payment.getParentId()));
//                    subscribeService.update(updateWrapper);
//
//                    procurementService.update(new UpdateWrapper<MergeProcurement>()
//                            .set("process_instance_id", process_instance_id)
//                            .eq("id", mergeProcurement.getId()));
                    return ResultVo.success("操作成功");
                }else{
                    return ResultVo.success("操作失败");
                }

            } catch (Exception e) {
                return ResultVo.fail(e.getMessage());
            }
        } else {
            // 修改请款申请状
            Subscribe subscribe = new Subscribe();
            subscribe.setId(payment.getId());
            subscribe.setPayType(payment.getPayType());
            subscribe.setPayStatus(2);
            subscribe.setStatus("1");
            subscribe.setTotalPrice(new BigDecimal("0"));
            subscribeMapper.updateById(subscribe);
            ordersService.update(new UpdateWrapper<PurchaseOrders>().set("payment_method", payment.getPayType())
                    .eq("parent_id", subscribe.getId()));
            // TODO  修改申请单
            goodsPoolService.update(new UpdateWrapper<GoodsPool>().set("status", 3)
                    .eq("id", payment.getParentId()));
            return ResultVo.success("已申请");
        }

    }


    public static void main(String[] args) {
        String str="oaIfyVhTQYOI6uuaKLy1-A03271684375344";
        if(StringUtils.isNotEmpty(str)){
            System.out.println("11");
        }else{
            System.out.println("22");
        }
    }
    /**
     * 请款申请通过
     */
    @Override
    public ResultVo PaymentAdopt(Integer id) {
        Payment payment = new Payment();
        payment.setAccountStatus(2);
        this.baseMapper.update(payment, new QueryWrapper<Payment>().eq("parent_id", id));
        Payment s = this.baseMapper.selectOne(new QueryWrapper<Payment>().eq("parent_id", id));
        Subscribe subscribe = new Subscribe();
        if (s != null) {
            subscribe.setTotalPrice(s.getMoney());
        }
        // 修改请款申请状
        subscribe.setId(id);
        subscribe.setStatus("1");
        subscribe.setPayStatus(2);
        subscribe.setTotalPrice(new BigDecimal("0"));
        //subscribe.setPayType(s.getPaymentMethod());
        subscribeMapper.updateById(subscribe);

        //
        //        // 采购清单
        //        List<PurchaseOrders> ordersList = commodityList.stream().map(item -> {
        //            PurchaseOrders orders = new PurchaseOrders();
        //            orders.setOrdersNumber(goodsPool.getSubscribeNumber().substring(2));
        //            orders.setParentId(subscribe.getId());
        //            orders.setGoodsPoolCommodityId(item.getId());
        //            orders.setGoodsTotalPrice(new BigDecimal(item.getCommodityAmount()).multiply(item
        //            .getCommodityPrice()));
        //            orders.setGoodsStatus(0);
        //            orders.setPurchaserId(subscribe.getPurchaserId());
        //            orders.setModifierBy("1");
        //            orders.setCreationTime(new Date());
        //            return orders;
        //        }).collect(Collectors.toList());
        //        purchaseOrdersService.saveBatch(ordersList);
        //
        return ResultVo.success("申请通过");
    }

    @Override
    public ResultVo test(Payment payment, BindingResult bindingResult) throws Exception {
        FundsDto fundsDto = new FundsDto();
        fundsDto.setAccess_token(DingDingUtil.obtainToken());
        fundsDto.setOriginator_userid(payment.getUserId());
        fundsDto.setDeptId(payment.getDeptId());
        fundsDto.setApprover_userid(payment.getApproval());
        fundsDto.setCc_userId(payment.getNotify());
        fundsDto.setCity("成都");
        fundsDto.setDepartment("研发部");
        fundsDto.setDate(payment.getDate());
        fundsDto.setCompanyName(payment.getCompanyName());
        fundsDto.setUrgency(payment.getUrgency());
        fundsDto.setReason(payment.getReason());
        fundsDto.setAmount(payment.getMoney().toString());
        fundsDto.setUnit(payment.getPayee());
        fundsDto.setBankName(payment.getOpeningBank());
        fundsDto.setBankAccount(payment.getAccountNumber());
        fundsDto.setPayType(payment.getPaymentMethod());

        System.out.println(JSONObject.toJSONString(fundsDto));

        String process_instance_id = DingDingUtil.OldPurchaseRequest(fundsDto);
        System.out.println(process_instance_id);  //WuDN-mTeRq-GqHkL6mKGGA03271669014228
        return null;
    }

    public String addDingDing(Payment payment) throws Exception {
        FundsDto fundsDto = new FundsDto();
        fundsDto.setAccess_token(DingDingUtil.obtainToken());
        fundsDto.setOriginator_userid(payment.getUserId());
        fundsDto.setDeptId(payment.getDeptId());
        fundsDto.setApprover_userid(payment.getApproval());
        fundsDto.setCc_userId(payment.getNotify());
        fundsDto.setCity(payment.getCity());// TODO
        fundsDto.setDepartment(payment.getDepartment());// TODO: 2020/3/26  部门
        fundsDto.setDate(payment.getDate());
        fundsDto.setCompanyName(payment.getCompanyName());
        fundsDto.setUrgency(payment.getUrgency());
        fundsDto.setReason(payment.getReason());
        fundsDto.setAmount(payment.getMoney().toString());
        fundsDto.setUnit(payment.getPayee());
        fundsDto.setBankName(payment.getOpeningBank());
        fundsDto.setBankAccount(payment.getAccountNumber());
        fundsDto.setPayType(payment.getPaymentMethod());
        System.out.println(JSONObject.toJSONString(fundsDto));
        String process_instance_id = DingDingUtil.OldPurchaseRequest(fundsDto);
        System.out.println(process_instance_id);  //WuDN-mTeRq-GqHkL6mKGGA03271669014228
        return process_instance_id;
    }
}
